#include "bsp_i2c_slave.h"



void BSP_I2C_Slave_Int_Callback(void)
{
    volatile uint8_t u8state = SYM_I2C1->STAT_f.STAT; 
    switch (u8state)
    {
    case SLAVE_I2C_ERROR:
        
        break;
    case SLAVE_I2C_STOP_RESTART:
        
        break;
    case SLAVE_I2C_WR_DEVADDR_ACK:
        SYM_I2C1->CR_f.STA = 0;
        if(g_i2c_msg.reglen > 0){
            SYM_I2C1->DR_f.DR = g_i2c_msg.preg[g_i2c_msg.regcnt];
            g_i2c_msg.regcnt++;
        }
        else{
            if(g_i2c_msg.len > 0){
                SYM_I2C1->DR_f.DR = g_i2c_msg.pdata[g_i2c_msg.txcnt];
                g_i2c_msg.txcnt++;
            }
            else{
                SYM_I2C1->CR_f.STO = 1;
            }
        }
        break;
    case MASTER_I2C_WR_DEVADDR_NAK:
    case MASTER_ARBITRATION_LOST:
    case MASTER_I2C_WR_DR_NAK:
    case MASTER_I2C_RD_DEVADDR_NAK:
//        SYM_I2C1->CR_f.STA = 1;
        SYM_I2C1->CR_f.STO = 1;
        break;
    case MASTER_I2C_RD_DR_NAK:
        g_i2c_msg.pdata[g_i2c_msg.rxcnt] = 0;
        g_i2c_msg.rxcnt++;
        SYM_I2C1->CR_f.STO = 1;
        break;
    case MASTER_I2C_WR_DR_ACK:
        if(g_i2c_msg.reglen > g_i2c_msg.regcnt){
             SYM_I2C1->DR_f.DR = g_i2c_msg.preg[g_i2c_msg.regcnt];
            g_i2c_msg.regcnt++;
        }else{
            if(g_i2c_msg.RW == I2C_WRITE){
                if(g_i2c_msg.len > g_i2c_msg.txcnt){
                    SYM_I2C1->DR_f.DR = g_i2c_msg.pdata[g_i2c_msg.txcnt];
                    g_i2c_msg.txcnt++;
                }
            }else{
                SYM_I2C1->CR_f.STA = 1;//Generate Restart
                SYM_I2C1->CR_f.STO = 0;
            }
        }
        break;
    case MASTER_I2C_RD_DEVADDR_ACK:
        SYM_I2C1->CR_f.AA = I2C_AA_ACK;
        break;
    case MASTER_I2C_RD_DR_ACK:
        g_i2c_msg.pdata[g_i2c_msg.rxcnt] = SYM_I2C1->DR_f.DR;
        g_i2c_msg.rxcnt++;
        if(g_i2c_msg.rxcnt == g_i2c_msg.len - 1){
            SYM_I2C1->CR_f.AA = I2C_AA_NAK;
        }
    default:
        break;
    } 
    SYM_I2C1->CR_f.SI = 0;   
}